const path = require('path')
const fs = require('fs')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('./plugins/html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const isProd = process.env.NODE_ENV === 'production'
const pages = fs.readdirSync('./src/pages')

// 获取module中处理css文件的rule
const getCssRule = useModule => (
  isProd ?
    [{
      loader: MiniCssExtractPlugin.loader,
      options: { publicPath: '../' }
    }] :
    ['style-loader']
).concat([
  {
    loader: 'css-loader',
    options: {
      modules: useModule ? {
        localIdentName: '[local]-[hash:base64:5]'
      } : false
    }
  },
  'postcss-loader'
])

module.exports = {
  mode: isProd ? 'production' : 'development',

  entry() {
    let v = {}
    pages.forEach(key => {
      v[key] = './src/pages/' + key + '/' + key + '.js'
    })
    return v
  },

  output: {
    filename: 'js/[name].js',
    chunkFilename: 'js/[name].js',
    path: path.resolve(__dirname, './dist')
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        use: ['ts-loader', 'jsx-loader']
      },
      {
        test: /\.css$/,
        exclude: [
          path.resolve(__dirname, './src/components')
        ],
        use: getCssRule(false)
      },
      {
        test: /\.css$/,
        include: [
          path.resolve(__dirname, './src/components')
        ],
        use: getCssRule(true)
      },
      {
        test: /\.(html)$/,
        loader: 'html-loader',
        options: {
          minimize: true // 压缩
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        loader: 'file-loader',
        options: {
          publicPath: '/asset/img/',
          name: '[name].[ext]?[hash:7]',
          emitFile: false
        }
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.json'],
    alias: {
      components: path.resolve(__dirname, './src/components/'),
      img: path.resolve(__dirname, './src/img/'),
      js: path.resolve(__dirname, './src/js/'),
      css: path.resolve(__dirname, './src/css/')
    }
  },

  devServer: {
    contentBase: './dist', // webpack服务器根目录
    host: '0.0.0.0',
    useLocalIp: true,
    proxy: [{
      context: ['/favicon.ico', '/asset', '/tmp'],
      target: 'https://ylmtst.mao-app.com',
      secure: false,
      changeOrigin: true, // 设置为true时，下面的headers设置才会生效
      headers: { // 确保headers里面所有的key全部小写
        host: 'ylmtst.mao-app.com',
        referer: 'https://ylmtst.mao-app.com/test.html'
      }
    }, { // api接口反向到测试服
      context: '/apiTesting',
      target: 'https://dev.mao-app.com',
      pathRewrite: { "^/apiTesting": "" },
      secure: false,
      changeOrigin: true,
      headers: {
        host: 'ylmtst.mao-app.com',
        referer: 'https://ylmtst.mao-app.com/test.html'
      }
    }, { // api接口反向到正式服
      context: '/apiOfficial',
      target: 'https://www.mao-app.com',
      pathRewrite: { "^/apiOfficial": "" },
      secure: false,
      changeOrigin: true,
      headers: {
        host: 'ylm.mao-app.com',
        referer: 'https://ylm.mao-app.com/test.html'
      }
    }]
  },

  plugins: [
    new CleanWebpackPlugin()
  ].concat(
    isProd ? [
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: 'css/[name].css',
        chunkFilename: 'css/[name].css',
      })
    ] : []
  ).concat(pages.map(
    page => new HtmlWebpackPlugin({
      filename: page + '.html',
      template: './src/pages/' + page + '/' + page + '.html',
      hash: true,
      chunks: [], // 默认为所有的chunks
      entries: [page] // 最终引入的chunk为entries涉及到的chunk和上面的chunks的并集
    })
  )),

  optimization: {
    splitChunks: {
      chunks: 'all'
    },
    runtimeChunk: 'single'
  }
}